// 后端客服API实现示例
// 这个文件展示了如何在后端集成第三方智能客服API

// 第三方AI服务配置
const AI_SERVICE_CONFIG = {
  // 阿里云智能客服
  ALIYUN: {
    baseUrl: 'https://nls-gateway.cn-shanghai.aliyuncs.com',
    appKey: process.env.ALIYUN_APP_KEY,
    accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET
  },
  
  // 腾讯云智能客服
  TENCENT: {
    baseUrl: 'https://hunyuan.cloud.tencent.com',
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
    appId: process.env.TENCENT_APP_ID
  },
  
  // 百度智能客服
  BAIDU: {
    baseUrl: 'https://aip.baidubce.com',
    apiKey: process.env.BAIDU_API_KEY,
    secretKey: process.env.BAIDU_SECRET_KEY
  },
  
  // 使用哪个服务商
  provider: process.env.AI_SERVICE_PROVIDER || 'ALIYUN'
}

// 客服会话管理
class CustomerServiceSession {
  constructor() {
    this.sessions = new Map()
    this.messageHistory = new Map()
  }
  
  // 创建新会话
  createSession(userId, userInfo = {}) {
    const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    const session = {
      id: sessionId,
      userId: userId,
      userInfo: userInfo,
      status: 'active',
      createdAt: new Date(),
      lastActivity: new Date(),
      messageCount: 0
    }
    
    this.sessions.set(sessionId, session)
    this.messageHistory.set(sessionId, [])
    
    return session
  }
  
  // 获取会话信息
  getSession(sessionId) {
    return this.sessions.get(sessionId)
  }
  
  // 更新会话活动时间
  updateSessionActivity(sessionId) {
    const session = this.sessions.get(sessionId)
    if (session) {
      session.lastActivity = new Date()
      session.messageCount++
    }
  }
  
  // 添加消息到历史记录
  addMessage(sessionId, message) {
    const history = this.messageHistory.get(sessionId) || []
    history.push({
      ...message,
      timestamp: new Date(),
      id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    })
    
    // 限制历史消息数量，避免内存占用过大
    if (history.length > 1000) {
      history.splice(0, history.length - 1000)
    }
    
    this.messageHistory.set(sessionId, history)
    this.updateSessionActivity(sessionId)
    
    return history[history.length - 1]
  }
  
  // 获取历史消息
  getHistoryMessages(sessionId, page = 1, pageSize = 20) {
    const history = this.messageHistory.get(sessionId) || []
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    
    return {
      messages: history.slice(startIndex, endIndex),
      total: history.length,
      page: page,
      pageSize: pageSize,
      hasMore: endIndex < history.length
    }
  }
  
  // 关闭会话
  closeSession(sessionId) {
    const session = this.sessions.get(sessionId)
    if (session) {
      session.status = 'closed'
      session.closedAt = new Date()
    }
  }
}

// 智能客服AI服务
class IntelligentCustomerService {
  constructor() {
    this.provider = AI_SERVICE_CONFIG.provider
    this.config = AI_SERVICE_CONFIG[this.provider]
  }
  
  // 获取AI回复
  async getAIResponse(sessionId, userMessage, context = []) {
    try {
      switch (this.provider) {
        case 'ALIYUN':
          return await this.callAliyunAI(sessionId, userMessage, context)
        case 'TENCENT':
          return await this.callTencentAI(sessionId, userMessage, context)
        case 'BAIDU':
          return await this.callBaiduAI(sessionId, userMessage, context)
        default:
          throw new Error(`不支持的AI服务商: ${this.provider}`)
      }
    } catch (error) {
      console.error('AI服务调用失败:', error)
      // 返回本地智能回复作为备用方案
      return this.getLocalAIResponse(userMessage, context)
    }
  }
  
  // 调用阿里云智能客服API
  async callAliyunAI(sessionId, userMessage, context) {
    const axios = require('axios')
    
    try {
      // 获取阿里云token
      const token = await this.getAliyunToken()
      
      // 构建请求数据
      const requestData = {
        appkey: this.config.appKey,
        format: 'json',
        sample_rate: 16000,
        enable_punctuation_prediction: true,
        enable_inverse_text_normalization: true,
        enable_voice_detection: true,
        user_id: sessionId,
        message: userMessage,
        context: context
      }
      
      const response = await axios.post(`${this.config.baseUrl}/stream/v1`, requestData, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
          'X-NLS-Token': token
        }
      })
      
      if (response.status === 200) {
        return {
          success: true,
          reply: response.data.result || '抱歉，我没有理解您的问题，请重新描述一下。',
          confidence: response.data.confidence || 0.8,
          intent: response.data.intent || 'general'
        }
      } else {
        throw new Error(`阿里云API调用失败: ${response.status}`)
      }
    } catch (error) {
      console.error('阿里云AI调用失败:', error)
      throw error
    }
  }
  
  // 调用腾讯云智能客服API
  async callTencentAI(sessionId, userMessage, context) {
    const axios = require('axios')
    
    try {
      // 构建请求数据
      const requestData = {
        app_id: this.config.appId,
        secret_id: this.config.secretId,
        secret_key: this.config.secretKey,
        messages: [
          ...context.map(msg => ({
            role: msg.isSelf ? 'user' : 'assistant',
            content: msg.content
          })),
          {
            role: 'user',
            content: userMessage
          }
        ],
        stream: false,
        temperature: 0.7,
        top_p: 0.8,
        max_tokens: 2048
      }
      
      const response = await axios.post(`${this.config.baseUrl}/hllm/v1/chat/completions`, requestData, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.config.secretId}`
        }
      })
      
      if (response.status === 200) {
        return {
          success: true,
          reply: response.data.choices?.[0]?.message?.content || '抱歉，我暂时无法回答您的问题。',
          confidence: 0.9,
          intent: 'general'
        }
      } else {
        throw new Error(`腾讯云API调用失败: ${response.status}`)
      }
    } catch (error) {
      console.error('腾讯云AI调用失败:', error)
      throw error
    }
  }
  
  // 调用百度智能客服API
  async callBaiduAI(sessionId, userMessage, context) {
    const axios = require('axios')
    
    try {
      // 获取百度AI的access_token
      const tokenResponse = await axios.post(`${this.config.baseUrl}/oauth/2.0/token`, {
        grant_type: 'client_credentials',
        client_id: this.config.apiKey,
        client_secret: this.config.secretKey
      })
      
      if (tokenResponse.status !== 200) {
        throw new Error('获取百度AI token失败')
      }
      
      const accessToken = tokenResponse.data.access_token
      
      // 调用百度AI对话接口
      const response = await axios.post(`${this.config.baseUrl}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions`, {
        messages: [
          ...context.map(msg => ({
            role: msg.isSelf ? 'user' : 'assistant',
            content: msg.content
          })),
          {
            role: 'user',
            content: userMessage
          }
        ],
        stream: false,
        temperature: 0.7,
        top_p: 0.8,
        max_tokens: 2048
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`
        }
      })
      
      if (response.status === 200) {
        return {
          success: true,
          reply: response.data.result || '抱歉，我暂时无法理解您的问题。',
          confidence: 0.9,
          intent: 'general'
        }
      } else {
        throw new Error(`百度AI API调用失败: ${response.status}`)
      }
    } catch (error) {
      console.error('百度AI调用失败:', error)
      throw error
    }
  }
  
  // 本地智能回复（备用方案）
  getLocalAIResponse(userMessage, context) {
    const message = userMessage.toLowerCase()
    
    // 基于关键词的智能回复
    if (message.includes('订单') || message.includes('下单')) {
      return {
        success: true,
        reply: '您好，关于订单问题，请提供订单号，我会为您查询详细信息。',
        confidence: 0.8,
        intent: 'order_inquiry'
      }
    }
    
    if (message.includes('退款') || message.includes('退货') || message.includes('换货')) {
      return {
        success: true,
        reply: '您好，关于退款/退货/换货问题，请提供订单号和具体原因，我们会尽快为您处理。',
        confidence: 0.8,
        intent: 'refund_request'
      }
    }
    
    if (message.includes('物流') || message.includes('发货') || message.includes('配送')) {
      return {
        success: true,
        reply: '您好，关于物流配送问题，请提供订单号，我会为您查询最新物流状态。',
        confidence: 0.8,
        intent: 'logistics_inquiry'
      }
    }
    
    if (message.includes('优惠券') || message.includes('折扣') || message.includes('活动')) {
      return {
        success: true,
        reply: '您好，目前我们有多种优惠活动，您可以在首页-优惠券中心查看并领取适合的优惠券。',
        confidence: 0.8,
        intent: 'coupon_inquiry'
      }
    }
    
    // 基于上下文的智能回复
    if (context.length > 0) {
      const lastMessage = context[context.length - 1]
      if (lastMessage.content.includes('订单号')) {
        return {
          success: true,
          reply: '感谢您提供订单号，我正在为您查询相关信息，请稍等片刻...',
          confidence: 0.9,
          intent: 'order_processing'
        }
      }
    }
    
    // 默认回复
    const defaultReplies = [
      '您好，我是智能客服助手，很高兴为您服务！请问有什么可以帮助您的？',
      '感谢您的咨询，我会尽力为您提供帮助。请详细描述您的问题。',
      '您好，我是您的专属客服助手，请问有什么需要帮助的吗？',
      '感谢您的耐心等待，我会尽快为您解答问题。'
    ]
    
    return {
      success: true,
      reply: defaultReplies[Math.floor(Math.random() * defaultReplies.length)],
      confidence: 0.6,
      intent: 'general'
    }
  }
  
  // 获取阿里云token
  async getAliyunToken() {
    // 实际使用时需要根据阿里云的认证方式实现
    // 这里返回一个示例token
    return 'example_token_' + Date.now()
  }
}

// 消息处理服务
class MessageProcessingService {
  constructor(sessionManager, aiService) {
    this.sessionManager = sessionManager
    this.aiService = aiService
  }
  
  // 处理用户消息
  async processUserMessage(sessionId, userMessage, userId) {
    try {
      // 获取会话信息
      let session = this.sessionManager.getSession(sessionId)
      if (!session) {
        // 创建新会话
        session = this.sessionManager.createSession(userId)
        sessionId = session.id
      }
      
      // 添加用户消息到历史记录
      const userMsg = this.sessionManager.addMessage(sessionId, {
        content: userMessage,
        type: 'text',
        isSelf: true,
        userId: userId
      })
      
      // 获取AI回复
      const history = this.sessionManager.getHistoryMessages(sessionId, 1, 10).messages
      const aiResponse = await this.aiService.getAIResponse(sessionId, userMessage, history)
      
      // 添加AI回复到历史记录
      const aiMsg = this.sessionManager.addMessage(sessionId, {
        content: aiResponse.reply,
        type: 'text',
        isSelf: false,
        userId: 'ai_service',
        confidence: aiResponse.confidence,
        intent: aiResponse.intent
      })
      
      return {
        success: true,
        sessionId: sessionId,
        userMessage: userMsg,
        aiResponse: aiMsg,
        session: session
      }
    } catch (error) {
      console.error('处理用户消息失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }
  
  // 处理图片消息
  async processImageMessage(sessionId, imageUrl, userId) {
    try {
      // 添加图片消息到历史记录
      const imageMsg = this.sessionManager.addMessage(sessionId, {
        content: imageUrl,
        type: 'image',
        isSelf: true,
        userId: userId
      })
      
      // 可以在这里添加图片识别功能
      const aiResponse = await this.aiService.getAIResponse(sessionId, '用户发送了一张图片', [])
      
      const aiMsg = this.sessionManager.addMessage(sessionId, {
        content: aiResponse.reply,
        type: 'text',
        isSelf: false,
        userId: 'ai_service',
        confidence: aiResponse.confidence,
        intent: aiResponse.intent
      })
      
      return {
        success: true,
        sessionId: sessionId,
        imageMessage: imageMsg,
        aiResponse: aiMsg
      }
    } catch (error) {
      console.error('处理图片消息失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }
}

// 导出服务实例
const sessionManager = new CustomerServiceSession()
const aiService = new IntelligentCustomerService()
const messageProcessor = new MessageProcessingService(sessionManager, aiService)

module.exports = {
  sessionManager,
  aiService,
  messageProcessor,
  AI_SERVICE_CONFIG
}
